<?php

namespace App\Http\Controllers\Api;

use App\Helpers\Api\TtMiniTrait;
use App\Http\Controllers\BaseController;
use App\Models\Merchant;
use App\Models\User;
use Carbon\Carbon;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AuthController extends BaseController
{
    use TtMiniTrait;
    public function code(Request $request)
    {
        $input = $request->input();
        \Log::info("login-param : " . var_export($input, true));
        $this->validate($request, [
            'code' => 'required'
        ]);
        $app = $this->ttMini();
        $response = $app->auth->session($input['code']);
        \Log::info(json_encode_cn($response));
        if ($response['error'] != '0') {
            \Log::error('code : ' . $input['code'] . " response : "  . var_export($response, true));
            return $this->failed($response['errmsg']);
        }
        return $this->success(['openid' => $response['openid']]);
    }

    public function wx_login(Request $request)
    {
        $rec_merchant_id = $request->input('relate_merchant_id', 0);
        $input = $request->input();
        if (!empty($input['user_id'])) {
            $user = User::find($input['user_id']);
            if (!$token = \Auth::guard('api')->fromUser($user)) {
                return $this->failed('登录失败', 401);
            }
            return $this->respondWithToken($token);
        }
        \Log::info("weixin-login-param : " . var_export($input, true));
        $this->validate($request, [
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ]);
        $app = $this->miniProgram();

        $session = $app->auth->session($request->code);
        \Log::info("weixin-session : " . var_export($session, true));
        if (isset($session['errcode']) &&  $session['errcode'] > 0)
            return $this->failed($session['errmsg']);
        try {
            $total = 0;
            $userInfo = $app->encryptor->decryptData(
                $session['session_key'],
                $request->iv,
                $request->encryptedData
            );
            \Log::info("weixin-decrypt : " . var_export($userInfo, true));
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed('网络异常，请重新操作');
        }

        $user = User::where('openid', $userInfo['openId'])->first();
        if (!$user) {
            if ($rec_merchant_id && $rec_merchant_id != $user->id)
                $total = 1;
            $user = new User();
            $user->openid = $userInfo['openId'];
            $user->nickname = $userInfo['nickName'];
            $user->gender = $userInfo['gender'];
            $user->avatar_url = $userInfo['avatarUrl'];
            $user->benefit_user = User::BENEFIT_USER;
            $user->platform = User::PLAT_WX;
            $user->save();
        } else {
            if (!$user->rec_merchant_id && $user->id != $rec_merchant_id ) {
                $user->rec_merchant_id = $rec_merchant_id;
                $total = 1;
                $user->save();
            }
        }
        if ($rec_merchant_id) {
            $rec_user = User::find($rec_merchant_id);
            if ($rec_user) {
                $rec_user->increment('child_count', $total);
                $rec_cache_key = $rec_user->getMorphClass() . ":" . $rec_user->id;
                \Cache::forget($rec_cache_key);
            }
        }
        $cache_key = $user->getMorphClass() . ":" . $user->id;
        \Cache::forget($cache_key);

        if (!$token = \Auth::guard('api')->fromUser($user)) {
            return $this->failed('登录失败', 401);
        }

        return $this->respondWithToken($token);
    }


    public function login(Request $request) {
        $input = $request->input();
        \Log::info("login-param : " . var_export($input, true));
        if (!empty($input['user_id'])) {
            $user = User::find($input['user_id']);
            if (!$token = \Auth::guard('api')->fromUser($user)) {
                return $this->failed('登录失败', 401);
            }
            return $this->respondWithToken($token);
        }
        \Log::info("weixin-login-param : " . var_export($input, true));
        $this->validate($request, [
            'openId' => 'required',
            'avatarUrl' => 'required',
            'nickName' => 'required',
        ]);
        $rec_merchant_id = $request->input('relate_merchant_id', 0);
        $userInfo = $request->input();

        $cache_key = 'login_open_id' . $userInfo['openId'];
        if (Redis::setnx($cache_key, 1)) {
            Redis::expire($cache_key, 3);
            try {
                $user = User::where('openid', $userInfo['openId'])->first();
                return \DB::transaction(function () use($user, $userInfo, $rec_merchant_id, $cache_key) {
                    $total = 0;
                    if (!$user) {
                        if ($rec_merchant_id)
                            $total = 1;
                        $user = new User();
                        $user->openid = $userInfo['openId'];
                        $user->nickname = $userInfo['nickName'];
                        $user->gender = $userInfo['gender'];
                        $user->avatar_url = $userInfo['avatarUrl'];
                        $user->city = $userInfo['city'] ?? '';
                        $user->province = $userInfo['province'] ?? '';
                        $user->country = $userInfo['country'] ?? '';
                        $user->language = $userInfo['language'] ?? '';
                        $user->rec_merchant_id = $rec_merchant_id;
                        $user->benefit_user = User::BENEFIT_DAREN;
                        $user->platform = User::PLAT_DY;
                        $user->save();
                    } else {
                        if (!$user->rec_merchant_id && $user->id != $rec_merchant_id ) {
                            $user->rec_merchant_id = $rec_merchant_id;
                            $total = 1;
                        }
                        $user->updated_at = Carbon::now();
                        $user->save();
                    }
                    if ($rec_merchant_id) {
                        $merchant = Merchant::find($rec_merchant_id);
                        if ($merchant) {
                            $merchant->increment('child_count', $total);
                        }
                    }
                    Redis::del($cache_key);
                    if (!$token = \Auth::guard('api')->fromUser($user)) {
                        return $this->failed('登录失败', 401);
                    }
                    return $this->respondWithToken($token);
                });
            } catch (\Exception $e) {
                Redis::del($cache_key);
                return $this->failed($e->getMessage());
            }
        } else {
           return $this->failed("登录失败，请重试");
        }
    }


    public function relate(Request $request) {
        $user = $this->getUser();
        $this->validate($request, [
            'phone'   => 'required',
            'password'  => 'required',
        ], [
            'phone.required' => '手机号为空',
            'password.required' => '密码为空'
        ]);
        $input = $request->only(['phone', 'password']);
        $merchant = Merchant::where('phone', $input['phone'])->where('raw_password', $input['password'])->first();
        if (!$merchant)
            return $this->failed('手机号或者密码为空');

        $user->relate_merchant_id = $merchant->id;
        $user->save();
        return $this->success(['user' => $user], '关联成功');
    }




}
